const crypto = require('crypto'),
      fs = require('fs'),
      func = require('./common.js');
      var _GET,_POST,_TOOL,_DIR,h;//GET/POST 参数,emma.js全局名称,全局目录名,全局html.js对象
      var outype;//输出类型
exports.main = (req,res) =>{
    _DIR = req.bind.dir;
    const tool = require(_DIR+'/module/emma.js');
    var HTML = tool.require('html');
    _TOOL = tool;    
    _GET = req.bind.__GET;
    if(tool.empty(_GET)) _GET = {};
    _POST = req.bind.__POST;
    if(tool.empty(_POST)) _POST = {};    
    outype = _GET['outype'];
    if('hex' != outype && 'base64' != outype && 'binary' != outype) outype = 'hex';
    h = new HTML();
    h.isMobile(req,tool);
    h.load({'title':'Crypto || '+Math.random()*100000,'js':['/public/jquery-1.12.4.min','/public/jutil','/node/public/js/crypto'],'css':'/node/public/css/crypto'});
    //req.setEncoding('utf-8');//无效相比=  h.appHead('<meta charset="utf-8">');
    h.appHead('<meta charset="utf-8">');
    var html = '';
    html += func.navlist(func.udata(req.url,'app'));
    html += `<p class="tabtool">
        <a href="/node/crypto">复原</a><a href="javascript:void(0);" id="cryptbtn">加密</a>
        <a href="javascript:void(0);" id="signbtn">签名</a>
    </p>`;
    html += jmForm();
    html += signForm();
    html += hashString();
    h.appBody(html);
    res.write(h.getHtml());
    //  清除函数缓存
    func.clear(__dirname+'/common.js');
    //return '自己使用res.end();';
}
//  加密表单
function jmForm(){
    var xhtml = '',
        pbk = uhash = id = ''
    ;
    secret = _GET['id'];
    if(secret){
        //  加密1
        const hash = crypto.createHmac('sha256', secret)
                    //.update('I love cupcakes')
                    .digest(outype);
        id = secret;
        if(hash) uhash = hash;

        const hash1 = crypto.createHmac('sha256', secret);
        var runtime = _DIR+'/.runtime/';
        _TOOL.mkdir(runtime);
        runtime += 'node/';
        _TOOL.mkdir(runtime);
        var hmac = runtime+'hmac.pswd';
        var pswd = '密码原文写入文本';
        if(!fs.existsSync(hmac)) fs.writeFileSync(hmac,pswd);
        else pswd = fs.readFileSync(hmac).toString();
        hash1.on('readable',() => {
            var d = hash1.read();
            var hmaced =  runtime+'hmac.depswd';
            if(d) fs.writeFileSync(hmaced,d.toString(outype));
        });
        hash1.write(pswd);
        hash1.end();
        //  加密2
        //iterations 迭代次数=    pbkdf2Sync(password, salt, iterations, keylen[, digest])=> 原文,盐值,迭代次数,字长   => 支持编码后的类型：   binary,base64,hex
        pbk = crypto.pbkdf2Sync(secret,'salt', 10, 20, 'sha512').toString(outype);
    }
    var hex = {'type':'radio','name':'outype','value':'hex','id':'othex'};
    var base64 = {'type':'radio','name':'outype','value':'base64','id':'otbase64'};
    var binary = {'type':'radio','name':'outype','value':'binary','id':'otbinary'};
    if('hex' == outype) hex['checked'] = 'checked';
    else if('base64' == outype) base64['checked'] = 'checked';
    else if('binary' == outype) binary['checked'] = 'checked';
    var cks = h.text(hex)+'<lable for="othex">hex</lable>';
    cks += h.text(base64)+'<lable for="otbase64">base64</lable>';
    cks += h.text(binary)+'<lable for="otbinary">binary</lable>';
    xhtml = `
        <form method="get" id="cryptodata">
            <input type="text" name="id" placeholder="数据原文" required="required" value="${id}">
            <br>${cks}
            <br><button type="submit">加密</button>
            <br><span><a href="javascript:void(0);" title="密文" id="hashed">${uhash}</a></span>
            <br>${pbk}
        </form>
    `;
    return xhtml;
}
function signForm(){
    var vsign = _POST['sign']? _POST['sign']:'';
    if(vsign){
        const sign = crypto.createSign('RSA-SHA256');
        sign.write(vsign);
        //sign.update(vsign);
        sign.end();

        //const private_key = getPrivateKeySomehow();
        
        const jsy = crypto.createECDH('secp521r1');
        const jsy_key = jsy.generateKeys('base64');
        //const jsy_key = jsy.getPrivateKey('hex');
        console.log(jsy.getPrivateKey('base64'));

        const private_key = '-----BEGIN EC PRIVATE KEY-----\n' +
        'MHcCAQEEIF+jnWY1D5kbVYDNvxxo/Y+ku2uJPDwS0r/VuPZQrjjVoAoGCCqGSM49\n' +
        'AwEHoUQDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNhB8i3mXyIMq704m2m52FdfKZ2\n' +
        'pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng==\n' +
        '-----END EC PRIVATE KEY-----\n';
        
        var stri = sign.sign(private_key, outype);
        //console.log(private_key,Math.random());
    }
    var xhtml = '<form method="post" id="signdata">';
    xhtml += h.text({'name':'sign','value':vsign,'required':'required'});
    if(vsign){
        xhtml += '<p>私钥</p>'+h.textarea({'text':private_key,'name':'private_key','cols':'100','rows':'6'});
        xhtml += '<p>加密后</p>'+h.textarea({'text':stri,'name':'string','cols':'100','rows':'6'});
    }else xhtml += h.text({'type':'submit','value':'签名'});
    xhtml += '</form>';
    return xhtml;
}
//  hash值
function hashString()
{
    var html = '<div>';
    html += '<p>the names of the supported hash algorithms(Node 加密所支持的hash 算法列表)</p>';
    const hashes = crypto.getHashes();
    html += '<ol><li>'+hashes.join('</li><li>')+'</li></ol>';
    html += '</div>';
    return html;
}